import React, { useRef } from 'react';

import { ReactComponent as Photo } from '@/assets/images/profile/Photo.svg';
import { ReactComponent as ProfileIcon } from '@/assets/images/shared/icon-profile.svg';
import { getIsAuth } from '@/entities/auth/model/selectors';
import { getUserProfile, getUserProfileState } from '@/entities/profile/model/selectors';
import { PremiumCard } from '@/pagesComponents/Course/ui/ActionCard/PremiumCard';
import { innerUrls } from '@/shared/constants/urls';
import { ModalContext } from '@/shared/context/ModalContext';
import { Modals } from '@/shared/interfaces';
import { getImageUrl } from '@/shared/lib/images';
import { useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, Loader } from '@/shared/ui';
import { TopModal } from '@/widgets/ModalPage';
import cn from 'classnames';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useWindowSize } from 'usehooks-ts';

import cs from './Avatar.module.scss';
import { Nav } from './Nav';

interface AvatarProps {
  isProfile?: boolean;
  handleOpenAvatarModal?: () => void;
  className?: string;
}

export const Avatar = ({ isProfile = false, handleOpenAvatarModal, className }: AvatarProps) => {
  const [isOpen, setIsOpen] = React.useState(false);

  const { isPremium } = useAppSelector(getUserProfile);

  const router = useRouter();
  const profile = useAppSelector(getUserProfile);
  const { width } = useWindowSize();
  const isAuth = useAppSelector(getIsAuth);
  const profileLoading = useAppSelector(getUserProfileState);

  const { id } = React.useContext(ModalContext);

  const containerRef = useRef<HTMLDivElement>(null);

  if (isProfile && handleOpenAvatarModal) {
    return (
      <div className={cn(className, cs.avatar_photo)} onClick={() => handleOpenAvatarModal()}>
        {' '}
        <span className={cs.badge}>
          <Photo />
        </span>
        {profileLoading.loading || !profile?.avatar ? (
          <Loader borderRadius={130} />
        ) : (
          <Image alt="" className={cs.avatar_photo} fill src={getImageUrl(profile?.avatar as string)} />
        )}
      </div>
    );
  }

  return (
    <>
      <span className={cs.avatar_container}>
        {isAuth === undefined && (
          <div className={cs.profile}>
            <div className={cs.avatar}>
              <Loader borderRadius={130} />
            </div>
          </div>
        )}
        {isAuth === true && (
          <div
            className={cn(cs.profile, cs.modal_container)}
            onClick={() => width > 1024 && router.push(innerUrls.profile('main'))}
            ref={containerRef}
          >
            <div className={cs.modal_wrapper}>
              <div className={cs.modal}>
                <Nav />
              </div>
            </div>
            <Button
              aria-label="Профиль"
              className={cs.avatar}
              onClick={() => {
                width < 768 && setIsOpen(!isOpen);
              }}
            >
              {profileLoading.loading || !profile.avatar ? (
                <Loader borderRadius={130} />
              ) : (
                <Image
                  alt="profile"
                  fill
                  sizes="(max-width: 768px) 48vw, (max-width: 1024px) 24vw, (max-width: 1366px) 12vw, 8vw"
                  src={getImageUrl(profile.avatar as string)}
                />
              )}
            </Button>
          </div>
        )}
        {isAuth === false && (
          <Button
            aria-label="Войти в аккаунт"
            className={cs.loginButton}
            data-testid="link-auth"
            href="/auth"
            link
            target="_self"
            variant={ButtonVariants.Login}
          >
            <ProfileIcon />
            <span className={cs.loginText}>Войти</span>
          </Button>
        )}
      </span>

      <TopModal handleClose={() => setIsOpen(false)} isOpen={isOpen && !(id && id !== Modals.ConfirmExitModal)}>
        <Nav />
        {!isPremium && <PremiumCard tab />}
      </TopModal>
    </>
  );
};
